from django.db.models.expressions import F
from django.http import JsonResponse
import json
from ..models import Paper, User, StuTeaRelation, Thumbup
from django.db.models import Q
from django.contrib.auth.hashers import make_password
from django.db import transaction


def etc_handle(request):
    if request.method == 'GET':
        request.params = request.GET
    else:
        request.params = json.loads(request.body)
    action = request.params.get('action')

    if action in action_handler_dict:
        if not request.user.is_authenticated:
            return JsonResponse(
                {'ret': 1, 'msg': '未登录'}, json_dumps_params={'ensure_ascii': False})
        if request.user.usertype not in [2000, 3000]:
            return JsonResponse(
                {'ret': 1, 'msg': '仅老师和学生可以操作'}, json_dumps_params={'ensure_ascii': False})
        return action_handler_dict[action](request)
    return JsonResponse({'ret': 1, 'msg': 'action参数错误'})

def getmyprofile(request):
    try:
        user = request.user
        usertype = user.usertype
        profile = {
            'userid': user.id,
            'username': user.username,
            'usertype': user.usertype,
            'realname': user.realname
        }
        if usertype == 3000:
            return JsonResponse(
                {'ret': 0, 'profile': profile}, json_dumps_params={'ensure_ascii': False})
        if usertype == 2000:
            teacher = StuTeaRelation.objects.filter(student_id=user.id).values('teacher_id', 'teacher__realname')
            if teacher:
                profile['teacher'] = {"id": teacher[0]['teacher_id'], "realname": teacher[0]['teacher__realname']}
            else:
                profile['teacher'] = {"id": -1, "realname": "尚未设置"}
            return JsonResponse(
                    {'ret': 0, 'profile': profile}, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def setmyprofile(request):
    try:
        user = request.user
        newdata = request.params['newdata']
        record = User.objects.filter(id=user.id)
        if 'password' in newdata:
            newdata['password'] = make_password(newdata['password'])
        with transaction.atomic():
            if 'teacherid' in newdata:
                teacherid = newdata.pop('teacherid')
                if user.usertype == 2000:
                    stutea = StuTeaRelation.objects.filter(student_id=user.id)
                    if stutea:
                        stutea.update(teacher_id=teacherid)
                    else:
                        stutea.create(student_id=user.id, teacher_id=teacherid)
            record.update(**newdata)
            return JsonResponse({'ret': 0})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def listteachers(request):
    try:
        qs = User.objects.filter(usertype=3000).values('id', 'realname')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(realname__contains=k)
            qs = qs.filter(query)
        items = list(qs)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def thumbuporcancel(request):
    try:
        user = request.user
        paperid = request.params['paperid']
        paper = Paper.objects.filter(id=paperid)
        record = Thumbup.objects.filter(paper_id=paperid, user_id=user.id)
        with transaction.atomic():
            if record:
                if record[0].thumbup:
                    record.update(thumbup=False)
                    paper.update(thumbupcount=F('thumbupcount')-1)
                else:
                    record.update(thumbup=True)
                    paper.update(thumbupcount=F('thumbupcount')+1)
            else:
                Thumbup.objects.create(paper_id=paperid, user_id=user.id)
                paper.update(thumbupcount=F('thumbupcount')+1)
            return JsonResponse({"ret": 0, "thumbupcount": paper[0].thumbupcount})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})


action_handler_dict = {
    'getmyprofile': getmyprofile,
    'setmyprofile': setmyprofile,
    'listteachers': listteachers,
    'thumbuporcancel': thumbuporcancel,
}